/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ManejoExc.EmpresaException;
import Negocio.Aplicacion;
import Negocio.Empresa;
import Negocio.Insumo;
import Negocio.Parcela;
import Negocio.Personal;
import java.sql.Date;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diego
 */
public class FrmAplicacion extends javax.swing.JDialog {
    private Empresa unaEmpresa;
    private Parcela unaParcela;
    private Personal unPersonal;
    private Insumo unInsumo;
    private Aplicacion unaAplicacion;
    DefaultTableModel modeltblAplicaciones = new DefaultTableModel();
    
    
    /**
     * Creates new form FrmAplicacion
     */
    public FrmAplicacion(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
     public FrmAplicacion(java.awt.Frame parent, boolean modal,Empresa unaEmpresa) {
        super(parent, modal);
        initComponents();
        this.unaEmpresa = unaEmpresa;
        this.modeltblAplicaciones.addColumn("Id");
        this.modeltblAplicaciones.addColumn("Parcela");
        this.modeltblAplicaciones.addColumn("Fecha");
        this.modeltblAplicaciones.addColumn("Personal");
        this.modeltblAplicaciones.addColumn("Insumo");
        this.modeltblAplicaciones.addColumn("Cantidad");
        this.TxtInsumo.setEditable(false);
        this.TxtParcela.setEditable(false);
        this.TxtPersonal.setEditable(false);
    }
     
    public void cargarTabla(){
        this.borrarTabla();
        Object[]fila= new Object[6];  
        //this.unaParcela.ordenarAplicaciones(1);
        for (Aplicacion miRegistro : this.unaParcela.getAplicaciones()) {
        //Iterator it = this.unaParcela.ordenarAplicaciones(1).iterator();
        //    while(it.hasNext()){
        //  Aplicacion miRegistro = (Aplicacion) it.next();
            fila[0] = miRegistro.getIdAplicacion();
            fila[1] = this.unaParcela.toString();
            fila[2] = miRegistro.fechaArg();
            fila[3] = miRegistro.getPersonal().toString();
            fila[4] = miRegistro.getInsumo().getTipoDeInsumo().toString();
            fila[5] = miRegistro.getCantidad();
            this.modeltblAplicaciones.addRow(fila);
        }
      this.TblAplicaciones.setModel(modeltblAplicaciones);
    }
    

     public void borrarTabla(){
         
         DefaultTableModel modelo2=(DefaultTableModel) this.TblAplicaciones.getModel();         
         int filas=TblAplicaciones.getRowCount();         
         for(int i=0; i<filas;i++){
             modelo2.removeRow(0);         
         }

    

    }
    public void setParcela(Parcela miParcela){
        this.unaParcela = miParcela;
        this.TxtParcela.setText(this.unaParcela.toString());
        this.cargarTabla();
    } 
    
    public void setPersonal (Personal miPersonal){
        this.unPersonal = miPersonal;
        this.TxtPersonal.setText(this.unPersonal.toString());
    }
    
    public void setInsumo(Insumo miInsumo){
        this.unInsumo = miInsumo;
        this.TxtInsumo.setText(this.unInsumo.toString());
    }
    
    public void borrarAplicacion(){
        //borro la aplicacion seleccionada
        this.unaParcela.borrarAplicacion(this.unaAplicacion);
        
    }
    
    public Object getSelectedValue(){        
        int row = TblAplicaciones.getSelectedRow();  
        return TblAplicaciones.getModel().getValueAt(row, 0);  
    }    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        CmbFecha = new datechooser.beans.DateChooserCombo();
        jLabel2 = new javax.swing.JLabel();
        TxtParcela = new javax.swing.JTextField();
        BtnFindParcela = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        TxtPersonal = new javax.swing.JTextField();
        BtnFindPersonal = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        TxtInsumo = new javax.swing.JTextField();
        BtnFindInsumo = new javax.swing.JButton();
        BtnGuardar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TblAplicaciones = new javax.swing.JTable();
        BtnCancel = new javax.swing.JButton();
        BtnBorrar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        TxtCantidad = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Fecha");

        jLabel2.setText("Parcela");

        BtnFindParcela.setText("...");
        BtnFindParcela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnFindParcelaActionPerformed(evt);
            }
        });

        jLabel3.setText("Personal");

        BtnFindPersonal.setText("...");
        BtnFindPersonal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnFindPersonalActionPerformed(evt);
            }
        });

        jLabel4.setText("Insumo");

        BtnFindInsumo.setText("...");
        BtnFindInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnFindInsumoActionPerformed(evt);
            }
        });

        BtnGuardar.setText("Guardar");
        BtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnGuardarActionPerformed(evt);
            }
        });

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        TblAplicaciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        TblAplicaciones.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TblAplicacionesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TblAplicaciones);

        BtnCancel.setText("Cancelar");
        BtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelActionPerformed(evt);
            }
        });

        BtnBorrar.setText("Borrar");
        BtnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnBorrarActionPerformed(evt);
            }
        });

        jLabel5.setText("Cantidad");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(CmbFecha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(TxtParcela, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                            .addComponent(TxtPersonal)
                            .addComponent(TxtInsumo))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(BtnFindParcela)
                            .addComponent(BtnFindPersonal)
                            .addComponent(BtnFindInsumo))
                        .addGap(24, 24, 24))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(BtnGuardar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BtnCancel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BtnBorrar)
                                .addGap(8, 8, 8)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(66, 66, 66)
                                .addComponent(TxtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(CmbFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(TxtParcela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BtnFindParcela))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(TxtPersonal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BtnFindPersonal))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(TxtInsumo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BtnFindInsumo))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(TxtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BtnBorrar)
                    .addComponent(BtnCancel)
                    .addComponent(BtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnGuardarActionPerformed
        // TODO add your handling code here:
        //Date unaFecha,Parcela unaParcela,Personal unPersonal,Insumo unInsumo, float cantidad
        try{
            if(this.unaAplicacion == null){
                this.CmbFecha.setFormat(3);
                Date unaFecha = Empresa.miUtilidadDeFechas.fechaDb(this.CmbFecha.getText());            
                this.unaEmpresa.nuevaAplicacion(unaFecha,this.unaParcela,this.unPersonal,this.unInsumo,Float.parseFloat(this.TxtCantidad.getText()));
                JOptionPane.showMessageDialog(this, "La operacion se realizo correctamente");
                this.TxtInsumo.setText("");
                this.TxtParcela.setText("");
                this.TxtPersonal.setText("");
                this.TxtCantidad.setText("");
                this.unInsumo=null;
                this.unPersonal=null;
                this.unaParcela=null;
            }else{
                Date unaFecha = Empresa.miUtilidadDeFechas.fechaDb(this.CmbFecha.getText());            
                this.unaAplicacion.ModificarAplicacion(unaFecha,this.unaParcela,this.unPersonal,this.unInsumo,Float.parseFloat(this.TxtCantidad.getText()));
                JOptionPane.showMessageDialog(this, "La operacion se realizo correctamente");
            }
            this.cargarTabla();
        }
         catch(EmpresaException ex){
             JOptionPane.showMessageDialog(this, ex.getMessage());
         }
         catch(Exception ex){
            JOptionPane.showMessageDialog(this, "Error: "+ex.getMessage());
            
        }
    }//GEN-LAST:event_BtnGuardarActionPerformed

    private void BtnFindParcelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnFindParcelaActionPerformed
        // TODO add your handling code here:
        FindParcela ventana = new FindParcela(this,true,this.unaEmpresa);
        ventana.setLocationRelativeTo(this);
        ventana.setVisible(true); 
                                    
    }//GEN-LAST:event_BtnFindParcelaActionPerformed

    private void BtnFindPersonalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnFindPersonalActionPerformed
        // TODO add your handling code here:
        FrmFindPersonal ventana = new FrmFindPersonal(this,true,this.unaEmpresa);
        ventana.setLocationRelativeTo(this);
        ventana.setVisible(true); 
    }//GEN-LAST:event_BtnFindPersonalActionPerformed

    private void BtnFindInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnFindInsumoActionPerformed
        // TODO add your handling code here:
                FrmFindInsumo ventana = new FrmFindInsumo(this,true,this.unaEmpresa);
        ventana.setLocationRelativeTo(this);
        ventana.setVisible(true); 
    }//GEN-LAST:event_BtnFindInsumoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void BtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelActionPerformed
        // TODO add your handling code here:
            this.TxtInsumo.setText("");
            this.TxtParcela.setText("");
            this.TxtPersonal.setText("");
            this.TxtCantidad.setText("");
            
            this.unInsumo=null;
            this.unPersonal=null;
            this.unaParcela=null;
            
            
    }//GEN-LAST:event_BtnCancelActionPerformed

    private void BtnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBorrarActionPerformed
        // TODO add your handling code here:
                int mc,bc,ch=1;
        mc = JOptionPane.QUESTION_MESSAGE;
        bc = JOptionPane.YES_NO_CANCEL_OPTION;
        ch = JOptionPane.showConfirmDialog (this, "Desea borrar la aplicacion seleccionada ?", "Confirmacion", bc, mc); 
        if(ch == 0){
        this.borrarAplicacion();
        this.TxtInsumo.setText("");
        this.TxtParcela.setText("");
        this.TxtPersonal.setText("");
        this.unInsumo=null;
        this.unPersonal=null;
        this.unaParcela=null;            
        this.cargarTabla();            
            JOptionPane.showMessageDialog(this, "La operacion se realizo correctamente");
        }
        
    }//GEN-LAST:event_BtnBorrarActionPerformed

    private void TblAplicacionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TblAplicacionesMouseClicked
        // TODO add your handling code here:
        try{
            this.unaAplicacion = this.unaParcela.obtenerAplicacion(Integer.parseInt(this.getSelectedValue().toString()));
            this.unPersonal = this.unaAplicacion.getPersonal();
            this.unInsumo = this.unaAplicacion.getInsumo();
            this.TxtInsumo.setText(this.unaAplicacion.getInsumo().toString());
            this.TxtParcela.setText(this.unaParcela.toString());
            this.TxtPersonal.setText(this.unaAplicacion.getPersonal().toString());
            this.TxtCantidad.setText(this.unaAplicacion.getCantidad().toString());
        }
        catch(EmpresaException ex){
             JOptionPane.showMessageDialog(this, ex.getMessage());        
        }
        catch (Exception ex){
            JOptionPane.showMessageDialog(this, ex.getMessage());        
        }
    }//GEN-LAST:event_TblAplicacionesMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void mains(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmAplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmAplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmAplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmAplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog 
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmAplicacion dialog = new FrmAplicacion(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnBorrar;
    private javax.swing.JButton BtnCancel;
    private javax.swing.JButton BtnFindInsumo;
    private javax.swing.JButton BtnFindParcela;
    private javax.swing.JButton BtnFindPersonal;
    private javax.swing.JButton BtnGuardar;
    private datechooser.beans.DateChooserCombo CmbFecha;
    private javax.swing.JTable TblAplicaciones;
    private javax.swing.JFormattedTextField TxtCantidad;
    private javax.swing.JTextField TxtInsumo;
    private javax.swing.JTextField TxtParcela;
    private javax.swing.JTextField TxtPersonal;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
